﻿using MvvmFoundation.Wpf;
using ServiceOperater.Helpers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;

namespace ServiceOperater.ViewModels
{

    // 例子: D:\Projects\KanqDesktopProjects\QueryZJK\ViewModels\MainViewModel.cs
    public sealed class MainViewModel : ObservableObject
    {
        public MainViewModel()
        {
            FileCollection = new ObservableCollection<FileTreeNodeViewModel>();

            // 加载默认目录下所有的service文件, 形成目录树形结构
            initServiceDataSource();

            instantiateCommand();


        }

        private void instantiateCommand()
        {
            OnTreeNodeSelectionChangedCommand = new RelayCommand<FileTreeNodeViewModel>((selectedFtnvm) =>
            {
                loadServiceXmlFile(selectedFtnvm);

            }, (selectedFtnvm) =>
            {
                // 目录点击无效
                return (!selectedFtnvm.IsDirectory);
            });
        }

        private void loadServiceXmlFile(FileTreeNodeViewModel selectedFtnvm)
        {
            // http://www.cnblogs.com/hnsongbiao/p/5636076.html
            var xmlFilePath = selectedFtnvm.FullPath;

            selectedFtnvm.ServiceCollection.Clear();

            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFilePath);
            XmlElement root = doc.DocumentElement;

            XmlNodeList serviceNodeList = root.SelectNodes("/service-config/service");
            foreach (XmlNode serviceNode in serviceNodeList)
            {
                var serviceId = serviceNode.Attributes["id"].InnerText;
                var sTnvm = new ServiceTreeNodeViewModel(serviceId);
                selectedFtnvm.ServiceCollection.Add(sTnvm);

                foreach (XmlNode actionNode in serviceNode.SelectNodes("action"))
                {
                    var aTnvm = constructActionTreeNodeViewModel(actionNode);
                    sTnvm.ActionChildren.Add(aTnvm);
                }
            }
        }

        private ActionTreeNodeViewModel constructActionTreeNodeViewModel(XmlNode actionNode)
        {
            var actionNameAttribute = actionNode.Attributes["name"];
            var actionName = actionNameAttribute == null ? " " : actionNameAttribute.InnerText;
            var aTnvm = new ActionTreeNodeViewModel(actionName);

            var propertyNodes = actionNode.SelectNodes("property");
            foreach (XmlNode propertyNode in propertyNodes)
            {
                var propName = propertyNode.Attributes["name"].InnerText;
                var propValue = propertyNode.Attributes["value"].InnerText;

                //            

                // 最好还是用这个, 有通知功能嘛
                //PropertyInfo pInfo = aTnvm.GetType().GetProperty(propName, BindingFlags.Public | BindingFlags.Instance);
                //Type pType = pInfo.PropertyType;
                //pInfo.SetValue(aTnvm, Convert.ChangeType(propValue, pType), null);

                FieldInfo fInfo = aTnvm.GetType().GetField(propName, BindingFlags.NonPublic | BindingFlags.Instance);
                Type fType = fInfo.FieldType;
                fInfo.SetValue(aTnvm, Convert.ChangeType(propValue, fType));
            }

            return aTnvm;
        }

        private void initServiceDataSource()
        {
            var list = new List<string>();

            string dirPath = @"D:\Projects\DAPT\src\config\service\";//文件夹的路径
            if (!Directory.Exists(dirPath))
            {
                string errorInfo = String.Format("[ {0} ] do not exist!", dirPath);
                App.Messenger.NotifyColleagues(MessengerToken.SHOW_DIALOG, errorInfo);
                return;
            }

            var directory = new DirectoryInfo(dirPath);
            constructTree(directory, FileCollection);
        }

        private void constructTree(DirectoryInfo di, ObservableCollection<FileTreeNodeViewModel> collection)
        {
            FileInfo[] fileInfoColleciton = di.GetFiles("*.xml");//指定类型
            foreach (FileInfo fileInfo in fileInfoColleciton)
            {
                collection.Add(constructTreeNode(fileInfo, null));
            }

            DirectoryInfo[] dirInfoColleciton = di.GetDirectories();//指定类型
            foreach (DirectoryInfo dirInfo in dirInfoColleciton)
            {
                var tnvm = constructTreeNode(dirInfo, null);
                collection.Add(tnvm);
                constructTree(dirInfo, tnvm.Children);
            }
        }

        private FileTreeNodeViewModel constructTreeNode(FileSystemInfo fileInfo, FileTreeNodeViewModel parent)
        {

            //string filename = name.Substring(0, fullname.LastIndexOf("."));//去掉后缀名。
            bool isDirectory = FileHelper.isDir(fileInfo.FullName);
            var tnvm = new FileTreeNodeViewModel(fileInfo.Name, fileInfo.FullName, isDirectory, parent);
            return tnvm;
        }

        #region Props
        // 必须如此, 但是为啥.
        private ObservableCollection<FileTreeNodeViewModel> fileCollection;
        public ObservableCollection<FileTreeNodeViewModel> FileCollection
        {
            get
            {
                return fileCollection;
            }
            set
            {
                if (fileCollection == value)
                {
                    return;
                }

                fileCollection = value;

                RaisePropertyChanged("FileCollection");
            }
        }
        //证号zh


        ////区县代码qxdm
        //private QXDM qxdm = QXDM.NANMING;
        //public QXDM QXDM
        //{
        //    get
        //    {
        //        return qxdm;
        //    }
        //    set
        //    {
        //        if (qxdm == value)
        //        {
        //            return;
        //        }

        //        qxdm = value;

        //        RaisePropertyChanged("QXDM");
        //    }
        //}

        //private DJLX djlx = default(DJLX);
        //public DJLX DJLX
        //{
        //    get
        //    {
        //        return djlx;
        //    }
        //    set
        //    {
        //        if (djlx == value)
        //        {
        //            return;
        //        }

        //        djlx = value;

        //        RaisePropertyChanged("DJLX");
        //    }
        //}


        #endregion

        #region Commands

        public RelayCommand<FileTreeNodeViewModel> OnTreeNodeSelectionChangedCommand { get; private set; }

        #endregion

        #region 枚举数据源
        //public IEnumerable<ValueDescription> QXDMList
        //{ get { return EnumHelper.GetAllValuesAndDescriptions<QXDM>(); } }

        //public IEnumerable<ValueDescription> DJLXList
        //{ get { return EnumHelper.GetAllValuesAndDescriptions<DJLX>(); } }
        #endregion
    }
}
